package flatlandRPG;

import javax.swing.SwingUtilities;
import java.util.ArrayList;
import java.awt.FontMetrics;
import java.awt.Color;
import javax.swing.BorderFactory;
import javax.swing.JLabel;

// -------------------------------------------------------------------------
/**
 * A class to display text in game.
 *
 * @author evant
 * @version Apr 24, 2011
 */
public class GameText
    extends JLabel
{
    private int    width;
    private String lastText;
    private String plainText;


    // ----------------------------------------------------------
    /**
     * Create a new GameText object to fit a given width and height.
     *
     * @param width
     *            the width of the text window
     */
    public GameText(int width)
    {
        super();
        this.width = width;
        plainText = "";
        lastText = "";
        setOpaque(true);
        setForeground(Color.WHITE);
        setBackground(Color.BLACK);
        setBorder(BorderFactory.createLineBorder(Color.WHITE));
        setHorizontalAlignment(JLabel.CENTER);
        setVisible(false);
    }


    // ----------------------------------------------------------
    /**
     * Sets the text of the label and formats it into multiple lines.
     *
     * @param text
     *            the text to display
     */
    public void setFormatedText(String text)
    {
        plainText = text;
        setText(addWrapping(text));
    }


    /**
     * Wraps the text to display properly. Also expands the label to show all of
     * the text
     */
    private String addWrapping(String text)
    {
        // No need to recalculate if the text hasn't changed
        if (text != lastText)
        {
            FontMetrics fm = getFontMetrics(getFont());
            String[] words = text.split(" +");
            ArrayList<String> lines = new ArrayList<String>();
            String line = "";
            for (String word : words)
            {
                int stringWidth =
                    SwingUtilities.computeStringWidth(fm, line + word);
                if (stringWidth < width - 20)
                {
                    line += " " + word;
                }
                else
                {
                    lines.add(line);
                    line = "";
                }
            }
            lines.add(line);

            String newText = "<html>";

            for (String l : lines)
            {
                newText += l + "<br>";
            }

            newText += "</html>";

            setBounds(10, 10, width - 20, (fm.getHeight() + 10) * lines.size());
            lastText = text;
            return newText;
        }
        return lastText;
    }


    /**
     * Returns the simple text instead of the formated text that is displayed.
     */
    @Override
    public String getText()
    {
        return plainText;
    }
}
